package com.grechur.wanandroidcompose.page


import android.util.Base64
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.grechur.wanandroidcompose.ui.theme.Purple200
import com.grechur.wanandroidcompose.ui.theme.Purple700
import com.grechur.wanandroidcompose.viewmodel.SearchViewModel
import com.grechur.wanandroidcompose.widget.ArticlePage
import com.grechur.wanandroidcompose.widget.FlowRow
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SearchPage(
    globalNavHostController: NavHostController,
    searchViewModel: SearchViewModel = viewModel(),
) {
    val appBarHeight = 56.dp
    val statusBarDp = with(LocalDensity.current) {
        WindowInsets.statusBars.getTop(this).toDp()
    }
    LaunchedEffect(Unit) {
        searchViewModel.getHotKey()
    }
    val context = LocalContext.current
    var key by remember {
        mutableStateOf("")
    }
    val coroutineScope = rememberCoroutineScope()
    Scaffold(topBar = {
        TopAppBar(title = {
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(40.dp)
            ) {
                Box(
                    modifier = Modifier
                        .height(40.dp)
                        .background(color = Color.White, shape = RoundedCornerShape(10.dp))
                        .weight(1f),
                    contentAlignment = Alignment.CenterStart
                ) {
                    BasicTextField(
                        value = TextFieldValue(//设置光标最后一行
                            key,
                            TextRange(key.length)
                        ),
                        onValueChange = { key = it.text },
                        maxLines = 1,
                        singleLine = true,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
                IconButton(
                    onClick = {
                        coroutineScope.launch {
                            searchViewModel.search(0, key)
                        }
                    },
                    modifier = Modifier
                        .padding(horizontal = 10.dp)
                        .size(40.dp)

                ) {
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = "搜索",
                        tint = Color.White
                    )
                }
            }
        },
            backgroundColor = Color.Transparent,
            elevation = 0.dp,
            modifier = Modifier
                .background(
                    Brush.linearGradient(
                        listOf(
                            Purple700, Purple200
                        )
                    )
                )
                .height(statusBarDp + appBarHeight)
                .padding(top = statusBarDp),
            navigationIcon = {
                IconButton(onClick = { globalNavHostController.popBackStack() }) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = "返回",
                        tint = Color.White
                    )
                }
            }
        )
    }) {
        LazyColumn(
            modifier = Modifier
                .padding(it)
                .navigationBarsPadding()
        ) {
            stickyHeader {
                if (searchViewModel.hotList.isSuccess) {
                    val hots = searchViewModel.hotList.getOrDefault(listOf())
                    FlowRow(modifier = Modifier.background(Color.White)) {
                        hots.forEach { article ->
                            Button(
                                onClick = {
                                    key = article.name ?: ""
                                    coroutineScope.launch {
                                        searchViewModel.search(0, key)
                                    }
                                },
                                modifier = Modifier.padding(end = 5.dp),
                                colors = ButtonDefaults.buttonColors(
                                    backgroundColor = Color.White,
                                    contentColorFor(backgroundColor = Color.Black)
                                )
                            ) {
                                Text(
                                    text = "${article.name}",
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        }
                    }
                } else {
                    Toast.makeText(
                        context,
                        "${searchViewModel.hotList.exceptionOrNull()?.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
            if (searchViewModel.searchList.isSuccess) {
                items(searchViewModel.searchList.getOrDefault(listOf())) { article ->
                    ArticlePage(
                        globalNavHostController = globalNavHostController,
                        article = article,
                        canCollect = false,
                        modifier = Modifier
                            .padding(horizontal = 10.dp)
                            .clickable {
                                val link = article.link ?: ""
                                val encode = Base64.encodeToString(
                                    link.toByteArray(),
                                    Base64.NO_WRAP
                                )
                                globalNavHostController.navigate("webView?url=$encode?name=${article.title}")

                            }
                    )
                }
            } else {
                Toast.makeText(
                    context,
                    "${searchViewModel.hotList.exceptionOrNull()?.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }

        }
    }
}

@Preview
@Composable
fun SearchPagePreview() {
    SearchPage(rememberNavController())
}

